#include <QtGui>
#include "QHexViewer.h"


#define HORIZONTAL_HEAD_COUNT 16

QHexViewer::QHexViewer(QWidget *parent) :
    QMainWindow(parent)
{
    setGeometry(100, 100, 800, 480);

    mMainWidget = new QWidget(this);
    mMainWidget->setGeometry(0,0,800,480);


    mStatusBar = new QLabel(mMainWidget);
    statusBar()->addWidget(mStatusBar,5);

    mLineEdit = new QLineEdit(mMainWidget);
    mLineEdit->setGeometry(10,10,650,20);
    mPushButton = new QPushButton(mMainWidget);
    mPushButton->setText("File");
    mPushButton->setGeometry(700,10,80,20);

    mStringWidget = new QPlainTextEdit(mMainWidget);
    mStringWidget->setGeometry(590, 40, 200, 400);

    mTableWidget = new QTableWidget(mMainWidget);
    mTableWidget->setGeometry(5,40,580,400);
    mTableWidget->setColumnCount(HORIZONTAL_HEAD_COUNT);

    for(int i = 0; i < HORIZONTAL_HEAD_COUNT; i++){
        mTableWidget->setColumnWidth(i, 36);
        QTableWidgetItem *item = new QTableWidgetItem();
        item->setText(QString("0x0%1").arg(i,0,16));
        mTableWidget->setHorizontalHeaderItem(i, item);
    }



    connect(mLineEdit,SIGNAL(textChanged(QString)),this,SLOT(setTableWidgetRow()));
    connect(mPushButton, SIGNAL(clicked()),this,SLOT(openFileDialog()));

}


void QHexViewer::openFileDialog(){
    QFileDialog dialog;
    dialog.setFileMode(QFileDialog::AnyFile);
    mFilePath = dialog.getOpenFileName(this,tr("Select Hex File"),".",tr("Hex File(*.hex)"));
    mLineEdit->insert(mFilePath);

}

void QHexViewer::setTableWidgetRow(){
    QFileInfo info(mFilePath);
    qint64 fileSize = info.size();
    mStatusBar->setText(QString("%1 BYTE").arg(fileSize));
    mTalbeRowCount = (fileSize/16);
    if((info.size()%16)){
        mTalbeRowCount++;
    }

    mTableWidget->setRowCount(mTalbeRowCount);

    QFile file(mFilePath);
    if(!file.open(QIODevice::ReadOnly)){
        return;
    }

    mStringWidget->clear();
    int rowIndex;
    int columnIndex;

    for(rowIndex = 0; rowIndex<mTalbeRowCount ; rowIndex++){
        for(columnIndex = 0; columnIndex<16; columnIndex++){
            if(!file.atEnd()){
                QByteArray fileByte = file.read(1);
                QTableWidgetItem *item = new QTableWidgetItem();
                QString temp = fileByte.toHex();
                item->setText(temp);
                mTableWidget->setItem(rowIndex,columnIndex,item);


            }
        }
    }

    file.seek(0);
    mStringWidget->appendPlainText(QString(file.readAll()));
    file.close();

}




